import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-flip-clock',
  templateUrl: './flip-clock.component.html',
  styleUrls: ['./flip-clock.component.less']
})
export class FlipClockComponent implements OnInit, OnDestroy {
  time: string[] = ['0', '0', '0', '0', '0', '0'];
  nextTime: string[] = ['0', '0', '0', '0', '0', '0'];
  flip: boolean[] = [false, false, false, false, false, false];
  private timer: any;

  constructor() { }

  ngOnInit(): void {
    this.updateTime();
    this.timer = setInterval(() => this.updateTime(), 1000);
  }

  ngOnDestroy(): void {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }

  private updateTime(): void {
    const now = new Date();
    const newTime = [
      ...this.padZero(now.getHours()),
      ...this.padZero(now.getMinutes()),
      ...this.padZero(now.getSeconds())
    ];
  
    for (let i = 0; i < 6; i++) {
      if (newTime[i] !== this.time[i]) {
        this.nextTime[i] = newTime[i];
        this.flip[i] = true;
        setTimeout(() => {
          this.time[i] = this.nextTime[i];
          this.flip[i] = false;
        }, 500);
      }
    }
  }

  private padZero(num: number): string[] {
    const str = num < 10 ? `0${num}` : num.toString();
    return [str[0], str[1]];
  }
}
